<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Guido
 * Date: 12/06/13
 * Time: 20:49
 * To change this template use File | Settings | File Templates.
 */

namespace dato;


class dato {

    protected $id;
    protected $nombre;
    protected $valor;
    protected $tableName;

    function __construct($id=0)
    {
        global $config;

        $this->id = 0;
        $this->nombre = "";
        $this->valor = "";
        $this->tableName = "`".$config["dbName"]."`.`datos`";

        if ($id != 0){
            $this->loadDato($id);
        }
    }

    public function loadDato($id)
    {
        global $db;

        $sSql = "select * from ".$this->tableName." where id = ". $id;

        $res = $db->execSql($sSql);

        if ($res){
            while ($row = mysqli_fetch_assoc($res)) {
                $this->setId($row["id"]);
                $this->setNombre($row["nombre"]);
                $this->setValor($row["valor"]);
            }
        }
    }

    public function saveData(){
        global $db;
        $rtrn = 0;
        if ($this->id==0){
            $sSql = "insert into ".$this->tableName." (nombre,valor) " .
                    " values ('$this->nombre','$this->valor') ";

            if ($db->execSql($sSql)){
                $rtrn = $db->getInsertedId();
            }
        }else{
            $sSql = "update ".$this->tableName." set ".
                "nombre= '".$this->nombre."',".
                "valor= '".$this->valor."' where id = " . $this->id;
            $db->execSql($sSql);
        }

        return $rtrn;
    }

    public function deleteDato(){
        global $db;
        $rtrn = false;
        if ($this->id != 0){
            $sSql = "delete from ".$this->tableName." where id = ". $this->id;
            if ($db->execSql($sSql)){
                $rtrn = true;
            }
        }
        return $rtrn;
    }


    /**
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param string $nombre
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;
    }

    /**
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }

    /**
     * @return string
     */
    public function getTableName()
    {
        return $this->tableName;
    }

    /**
     * @param string $valor
     */
    public function setValor($valor)
    {
        $this->valor = $valor;
    }

    /**
     * @return string
     */
    public function getValor()
    {
        return $this->valor;
    }



}